package com.app.micaihu.custom.components.net;

import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.app.micaihu.base.bean.DataBean;
import com.app.utils.util.LogUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.lang.reflect.Type;

/**
 * 制作一个 Gson的get请求
 * Makes a get request and converts the response from JsonElement into a
 * list of objects/object using with Google Gson.
 * Created by kai on 2016/6/12.
 */
public class GsonGetRequest<T> extends Request<T> {
    private final Gson gson;
    private final Type type;
    private final Response.Listener<T> listener;

    /**
     * Make a GET request and return a parsed object from JSON.
     *
     * @param url           URL of the request to make
     * @param type          is the type of the object to be returned
     * @param listener      is the listener for the right answer
     * @param errorListener is the listener for the wrong answer
     */
    public GsonGetRequest
    (
            @NonNull final String url,
            @NonNull final Type type,
            @NonNull final Gson gson,
            @NonNull final Response.Listener<T> listener,
            @NonNull final Response.ErrorListener errorListener
    ) {
        super(Method.GET, url, errorListener);

        this.gson = gson;
        this.type = type;
        this.listener = listener;
    }

    @Override
    protected void deliverResponse(T response) {
        if (this.listener != null) {
            listener.onResponse(response);
        }
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {

        try {
//            String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            String json = new String(response.data);

            if (TextUtils.isEmpty(json)) {
                LogUtils.e("result", "->" + json);
                json = DataBean.getDefaultJson();
            }
            /***
             * 如果解析的json为 空字符串或者null，返回null 执行成功的回调函数
             * 目前json不为空,成功的回调函数返回值不为null
             * 如果解析的json格式不对，执行失败的回调函数
             * 如果type为null执行 失败的回调函数
             */
            return (Response<T>) Response.success
                    (
                            gson.fromJson(json, type),
                            HttpHeaderParser.parseCacheHeaders(response)
                    );
        }
//        catch (UnsupportedEncodingException e)
//        {
//            return Response.error(new ParseError(e));
//        }
        catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }

}
